from django.db import models

from apps.lookups.calendars.handlers import get_weekday_index
from bases.model import APIModel


class CalendarType(APIModel):
    calendar_type = models.CharField(verbose_name='日历类型', max_length=1, unique=True)
    calendar_name = models.CharField(verbose_name='日历类型名称', max_length=50)
    holiday = models.CharField(verbose_name='休息日', max_length=7, blank=True, null=True)

    class Meta:
        db_table = 'calendar_types'
        verbose_name = '日历类型'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.calendar_type} - {self.calendar_name}'

    @property
    def exist_calendar(self):
        return Calendar.objects.filter(calendar_type__calendar_type__exact=self.calendar_type).exists()


class CalendarDateType(models.TextChoices):
    """
    日历日期类型
    """
    WORKDAY = 'W', 'Workday',
    HOLIDAY = 'H', 'Holiday'


class Calendar(APIModel):
    calendar_type = models.ForeignKey(CalendarType, verbose_name='日历类型', on_delete=models.DO_NOTHING, db_index=True)
    calendar_date = models.DateField(verbose_name='日历日期', db_index=True)
    date_type = models.CharField(verbose_name='日期类型', max_length=1, choices=CalendarDateType.choices, db_index=True)
    date_seq = models.IntegerField(verbose_name='日期序号')
    workday_seq = models.IntegerField(verbose_name='工作日序号', default=0)

    class Meta:
        db_table = 'calendars'
        verbose_name = '日历'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.calendar_type.calendar_type} - {self.calendar_date} - {self.get_date_type_display()}'

    def is_holiday(self):
        return self.date_type == CalendarDateType.HOLIDAY

    def is_workday(self):
        return self.date_type == CalendarDateType.WORKDAY

    @property
    def weekday_index(self):
        return get_weekday_index(str(self.calendar_date))
